// 支持外部自定义传入加载提示的HTML内容或者使用默认样式
// 支持i18n多语言文本提示
// 导入ElementUI、外部公共样式以及图片icon
// 地址：https://element.eleme.cn/#/zh-CN/component/loading

import { Loading } from 'element-ui';
import '../../assets/css/Common/Notice/Loading.scss';
import { i18n } from '@/lang/index';
import checkImage from '@/static/image/HomePlayBack/PlaybackList/check.png';

let loadingInstance;
let isClose = true;

const defaultOptions = {
  fullscreen: true,
  target: document.body,
  lock: true,
  text: i18n.t('loading_text'),
  body: false,
  spinner: 'el-icon-loading',
  background: 'rgba(0, 0, 0, 0)',
  customClass: 'default-loading-box',
  customTemplate: `
    <div class="loading-icon">
      <img class="loading-img" src="${checkImage}" alt="">
    </div>
  `,
};

export default {
  open(msg = '', positionRight, customTemplate = defaultOptions.customTemplate) {
    isClose = false;
    const options = { ...defaultOptions, ...(this.option || {}), customTemplate };

    if (positionRight === "right") {
      options.customClass += ' right-position';
    }

    if (!loadingInstance) {
      // 需要调用时
      loadingInstance = Loading.service(options);
      if (customTemplate) {
        addCustomLoadingElement(loadingInstance, customTemplate);
      }
      if (msg) {
        loadingInstance.text = msg;
      }
    }
  },

  close() {
    isClose = true;
    setTimeout(() => {
      if (loadingInstance && isClose) {
        loadingInstance.close();
        loadingInstance = null;
        this.option = { ...defaultOptions };
      }
    }, 100);
  },

  changeMsg(msg) {
    if (loadingInstance) {
      loadingInstance.text = msg;
    } else {
      this.open(msg);
    }
  },

  changeIcon(icon) {
    if (loadingInstance) {
      loadingInstance.spinner = icon;
    }
  },
};

function addCustomLoadingElement(instance, template) {
  const divLoading = document.createElement("div");
  divLoading.innerHTML = template.replace(/\$\{checkImage\}/g, checkImage); // 替换模板中的占位符
  instance.$el.firstChild.prepend(divLoading);
}